import java.util.concurrent.*;

/**
 * @auther: Alessio
 * @date: 2021/1/18
 * 第四种获得Java多线程的方式，线程池
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool =new ThreadPoolExecutor(2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<Runnable>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        try {
            //模拟10个用户办理业务，每个用户就是一个来自外部的请求
            for (int i = 1; i <= 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t 办理业务");
                });
                // TimeUnit.MILLISECONDS.sleep(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    private static void executorInit() {
        //ExecutorService threadPool = Executors.newFixedThreadPool(5); //1池5个处理线程
        //ExecutorService threadPool = Executors.newSingleThreadExecutor(); //1池1个处理线程
        ExecutorService threadPool = Executors.newCachedThreadPool();//1池N个处理线程
        try {
            //模拟10个用户办理业务，每个用户就是一个来自外部的请求
            for (int i = 1; i <= 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t 办理业务");
                });
               // TimeUnit.MILLISECONDS.sleep(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
